package jus.aor.mobilagent.kernel;

import java.io.IOException;
import java.io.ObjectOutputStream;
import java.net.InetAddress;
import java.net.Socket;
import java.io.Serializable;
import java.net.URI;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;

public class Agent implements _Agent,Serializable{

	private static final long serialVersionUID = -3789916539516520489L;
	
	private ArrayList<Etape> listeEtape = new ArrayList<Etape>();

	private transient BAMLoader loader;
	
	private transient AgentServer agentServer;
	
	private String serverName;
	
	
	@Override
	public void run() {
		if(!listeEtape.isEmpty()){
			listeEtape.get(0).action.execute();
			listeEtape.remove(0);
			if(!listeEtape.isEmpty())
				sendMe();
		}
	}

	private void sendMe(){
		URI uri = listeEtape.get(0).server;
		try {
			Socket s = new Socket(uri.getHost(), uri.getPort());
			ObjectOutputStream oop = new ObjectOutputStream(s.getOutputStream());
			if(loader==null)
				System.err.println("loader NULL");
			if(loader.extractCode()==null)
				System.err.println("extract null");
			oop.writeObject(loader.extractCode());
			oop.writeObject(this);
		} catch (UnknownHostException e) {
			e.printStackTrace();
			try {
				Logger logger=Logger.getLogger("jus/aor/mobilagent/"+InetAddress.getLocalHost().getHostName()+"/"+agentServer.nameServer);
				logger.log(Level.FINE, "Agent - sendMe :", e);
			} catch (UnknownHostException ex) {};
		} catch (IOException e) {
			e.printStackTrace();
			try {
				Logger logger=Logger.getLogger("jus/aor/mobilagent/"+InetAddress.getLocalHost().getHostName()+"/"+agentServer.nameServer);
				logger.log(Level.FINE, "Agent - sendMe :", e);
			} catch (UnknownHostException ex) {};
		}
	}
	
	@Override
	public void init(AgentServer agentServer, String serverName) {
		init((BAMLoader)this.getClass().getClassLoader(),agentServer,serverName);		
	}

	@Override
	public void init(BAMLoader loader, AgentServer server, String serverName) {
		this.loader=loader;
		this.agentServer=server;
		this.serverName=serverName;
	}

	@Override
	public void addEtape(Etape etape) {
		listeEtape.add(etape);
	}

	public String getServerName(){
		return serverName;
	}

}
